﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;

namespace DiArte.Data
{
    public abstract class BaseDal
    {
        /// <summary>
        /// Performs a single command
        /// </summary>
        /// <param name="command">The command to perform</param>
        protected void PerformCommand(Npgsql.NpgsqlCommand command)
        {
            using (var connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
            {
                connection.Open();

                command.Connection = connection;
                command.ExecuteNonQuery();

                connection.Close();
            }
        }

        /// <summary>
        /// Performs a single command and gets the returning id
        /// </summary>
        /// <param name="command">The command to perform</param>
        protected int PerformInsertCommandAndGetReturningValue(Npgsql.NpgsqlCommand command)
        {
            using (var connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
            {
                int? id = null;

                connection.Open();

                command.Connection = connection;

                using (var dataAdapter = new Npgsql.NpgsqlDataAdapter(command))
                {
                    using (var dataSet = new DataSet())
                    {
                        dataAdapter.Fill(dataSet);

                        id = dataSet.Tables[0].Rows[0].Field<int>(0); 
                    }
                }

                connection.Close();

                return id.Value;
            }
        }

        /// <summary>
        /// Gets the database connection string
        /// </summary>
        /// <returns>A connection string</returns>
        private String GetConnectionString()
        {
            return ConfigurationManager.ConnectionStrings["DiArte"].ConnectionString;
        }

    }
}
